<template>
  <div class="app-container">
    <!-- 筛选条件区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" label-width="90px" class="mb10" v-show="showSearch">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="协议编码" prop="frameworkCode">
            <el-input v-model="queryParams.frameworkCode" clearable placeholder="请输入协议编码"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货公司" prop="receiverCompanyName">
            <el-input v-model="queryParams.receiverCompanyName" clearable placeholder="请输入收货公司名称"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货公司" prop="senderCompanyName">
            <el-input v-model="queryParams.senderCompanyName" clearable placeholder="请输入发货公司名称"
              @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="请选择状态" @change="handleQuery"
              @clear="handleQuery">
              <el-option v-for="dict in dict.type.protocol_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="协议日期">
            <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
              start-placeholder="协议开始日期" end-placeholder="协议结束日期" @change="handleQuery" @clear="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 工具栏区域 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="12">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['kanban:supplyFramework:add']">新建协议</el-button>
        <el-button type="success" icon="el-icon-refresh" size="mini" @click="getList">刷新数据</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-col>
    </el-row>

    <!-- 数据列表区域 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="协议编码" prop="frameworkCode" min-width="150">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.frameworkCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="收货公司" prop="receiverCompanyName" min-width="160" />
      <el-table-column label="发货公司" prop="senderCompanyName" min-width="160" />
      <el-table-column label="协议状态" prop="status" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.protocol_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="生效时间" prop="businessStartDate" width="130" />
      <el-table-column label="到期时间" prop="businessEndDate" width="130" />
      <el-table-column label="创建人" prop="createBy" width="120" />
      <el-table-column label="创建时间" prop="createTime" width="160" />
      <el-table-column label="操作" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" @click="handleView(scope.row)">
            查看</el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kanban:framework:edit']">编辑</el-button>
          <!-- 确认按钮：只有当前用户为发货方且协议状态为待确认时才显示 -->
          <el-button type="text" size="mini" icon="el-icon-circle-check" @click="handleConfirm(scope.row)"
            v-if="scope.row.status === 20 && isCurrentUserReceiver(scope.row)"
            v-hasPermi="['kanban:framework:edit']">确认</el-button>
          <el-button type="text" size="mini" icon="el-icon-close" @click="handleVoid(scope.row)"
            v-hasPermi="['kanban:framework:edit']">作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 编辑抽屉 -->
    <el-drawer :title="editDrawerTitle" :visible.sync="editDrawerVisible" direction="rtl" size="60%"
      :before-close="handleEditDrawerClose">
      <!-- 保存状态遮罩层 -->
      <div v-if="isSaving" class="saving-mask">
        <div class="saving-content">
          <el-icon class="is-loading">
            <i class="el-icon-loading"></i>
          </el-icon>
          <div class="saving-text">{{ savingText }}</div>
        </div>
      </div>
      
      <div class="drawer-content">
        <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px">
          <!-- 基础信息区域 -->
          <div class="form-header">基础信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="协议编码" prop="frameworkCode">
                <el-input v-model="editForm.frameworkCode" disabled placeholder="系统自动生成，不可修改" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协议状态" prop="status">
                <el-select v-model="editForm.status" placeholder="请选择">
                  <el-option v-for="dict in dict.type.protocol_status" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="需求计划部门" prop="receiverDeptId">
                <treeselect v-model="editForm.receiverDeptId" :options="deptOptions" :normalizer="normalizer"
                  placeholder="请选择需求计划部门" @input="handleReceiverDeptChange" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货计划部门" prop="senderDeptId">
                <treeselect v-model="editForm.senderDeptId" :options="deptOptions" :normalizer="normalizer"
                  placeholder="请选择发货计划部门" @input="handleSenderDeptChange" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货公司" prop="receiverCompanyName">
                <el-input v-model="editForm.receiverCompanyName" placeholder="选择部门后自动填充" readonly disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货公司" prop="senderCompanyName">
                <el-input v-model="editForm.senderCompanyName" placeholder="选择部门后自动填充" readonly disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货仓库" prop="receiverWarehouseName">
                <el-input v-model="editForm.receiverWarehouseName" placeholder="请输入收货仓库" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货仓库" prop="senderWarehouseName">
                <el-input v-model="editForm.senderWarehouseName" placeholder="请输入发货仓库" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货联系人" prop="receiverContact">
                <el-input v-model="editForm.receiverContact" placeholder="请输入收货联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货联系人" prop="senderContact">
                <el-input v-model="editForm.senderContact" placeholder="请输入发货联系人" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">

            <el-col :span="12">
              <el-form-item label="收货电话" prop="receiverPhone">
                <el-input v-model="editForm.receiverPhone" placeholder="请输入收货联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货电话" prop="senderPhone">
                <el-input v-model="editForm.senderPhone" placeholder="请输入发货联系电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 时间配置 -->
          <div class="form-header">时间配置</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生效时间" prop="businessStartDate">
                <el-date-picker v-model="editForm.businessStartDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择生效日期" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期时间" prop="businessEndDate">
                <el-date-picker v-model="editForm.businessEndDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择到期日期" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 业务配置 -->
          <div class="form-header">业务配置</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="要货提前期(小时)" prop="leadTimeHours">
                <el-input-number v-model="editForm.leadTimeHours" :min="0" :max="240" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打印机ID" prop="printerId">
                <el-input v-model="editForm.printerId" placeholder="请输入打印机ID" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="箱标模板" prop="boxLabelTemplate">
                <el-input v-model="editForm.boxLabelTemplate" placeholder="请选择模板或填写" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="看板模板" prop="kanbanTemplate">
                <el-input v-model="editForm.kanbanTemplate" placeholder="请选择模板或填写" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="需确认协议" prop="needSenderConfirmFramework">
                <el-switch v-model="editForm.needSenderConfirmFramework" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需确认看板" prop="needSenderConfirmKanban">
                <el-switch v-model="editForm.needSenderConfirmKanban" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="当做送货单" prop="deliveryAsReceipt">
                <el-switch v-model="editForm.deliveryAsReceipt" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="收货扫码要求" prop="scanRequirement">
                <el-select v-model="editForm.scanRequirement" placeholder="请选择">
                  <el-option label="必须扫码" :value="1" />
                  <el-option label="建议扫码" :value="2" />
                  <el-option label="不要求" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

        <!-- 物料明细区域 -->
        <div class="form-header">物料明细</div>
        <div class="material-detail-section">
          <!-- 工具栏 -->
          <div class="material-toolbar">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddMaterial">添加物料</el-button>
            <el-button type="success" size="mini" icon="el-icon-upload2" @click="handleImportMaterial">Excel导入</el-button>
            <el-button type="warning" size="mini" icon="el-icon-download" @click="handleExportTemplate">下载模板</el-button>
          </div>
          
          <!-- 物料明细表格 -->
          <el-table :data="materialList" border size="mini" max-height="300" class="material-table">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="物料编码" prop="materialCode" width="120">
              <template slot-scope="scope">
                <el-input 
                  v-if="scope.row.editing" 
                  v-model="scope.row.materialCode" 
                  size="mini" 
                  placeholder="请输入物料编码"
                  maxlength="50"
                  show-word-limit />
                <span v-else>{{ scope.row.materialCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="物料名称" prop="materialName" width="150">
              <template slot-scope="scope">
                <el-input 
                  v-if="scope.row.editing" 
                  v-model="scope.row.materialName" 
                  size="mini" 
                  placeholder="请输入物料名称"
                  maxlength="100"
                  show-word-limit />
                <span v-else>{{ scope.row.materialName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="materialUnit" width="80">
              <template slot-scope="scope">
                <el-input 
                  v-if="scope.row.editing" 
                  v-model="scope.row.materialUnit" 
                  size="mini" 
                  placeholder="单位"
                  maxlength="10" />
                <span v-else>{{ scope.row.materialUnit }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单价" prop="unitPrice" width="100">
              <template slot-scope="scope">
                <el-input-number 
                  v-if="scope.row.editing" 
                  v-model="scope.row.unitPrice" 
                  size="mini" 
                  :precision="2" 
                  :min="0" 
                  :max="999999.99"
                  placeholder="0.00" />
                <span v-else>{{ scope.row.unitPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="税率(%)" prop="taxRate" width="80">
              <template slot-scope="scope">
                <el-input-number 
                  v-if="scope.row.editing" 
                  v-model="scope.row.taxRate" 
                  size="mini" 
                  :precision="2" 
                  :min="0" 
                  :max="100"
                  placeholder="0" />
                <span v-else>{{ scope.row.taxRate }}%</span>
              </template>
            </el-table-column>
            <el-table-column label="包装类型" prop="packageType" width="100">
              <template slot-scope="scope">
                <el-input 
                  v-if="scope.row.editing" 
                  v-model="scope.row.packageType" 
                  size="mini" 
                  placeholder="包装类型"
                  maxlength="20" />
                <span v-else>{{ scope.row.packageType }}</span>
              </template>
            </el-table-column>
            <el-table-column label="包装容量" prop="packageCapacity" width="100">
              <template slot-scope="scope">
                <el-input-number 
                  v-if="scope.row.editing" 
                  v-model="scope.row.packageCapacity" 
                  size="mini" 
                  :min="0"
                  :max="999999"
                  placeholder="0" />
                <span v-else>{{ scope.row.packageCapacity }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最小订货量" prop="minOrderQty" width="120">
              <template slot-scope="scope">
                <el-input-number 
                  v-if="scope.row.editing" 
                  v-model="scope.row.minOrderQty" 
                  size="mini" 
                  :min="0"
                  :max="999999"
                  placeholder="0" />
                <span v-else>{{ scope.row.minOrderQty }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <div v-if="scope.row.editing">
                  <el-button type="text" size="mini" @click="handleSaveMaterial(scope.row, scope.$index)">保存</el-button>
                  <el-button type="text" size="mini" @click="handleCancelEditMaterial(scope.row, scope.$index)">取消</el-button>
                </div>
                <div v-else>
                  <el-button type="text" size="mini" @click="handleEditMaterial(scope.row, scope.$index)">编辑</el-button>
                  <el-button type="text" size="mini" @click="handleDeleteMaterial(scope.$index)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Excel导入对话框 -->
        <el-dialog title="Excel批量导入物料" :visible.sync="importDialogVisible" width="600px" :close-on-click-modal="false" append-to-body>
          <div class="import-content">
            <div class="import-tips">
              <el-alert
                title="导入说明"
                type="info"
                :closable="false"
                show-icon>
                <div slot="description">
                  <p>1. 请先下载模板文件，按照模板格式填写物料信息</p>
                  <p>2. 支持的文件格式：.xlsx、.xls</p>
                  <p>3. 导入时会自动验证数据格式和必填字段</p>
                  <p>4. 物料编码不能重复，重复的数据将被跳过</p>
                </div>
              </el-alert>
            </div>
            
            <div class="import-actions" style="margin: 20px 0;">
              <el-button type="warning" icon="el-icon-download" @click="handleExportTemplate">下载导入模板</el-button>
            </div>
            
            <el-upload
              ref="uploadRef"
              :file-list="uploadFileList"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :before-upload="beforeUpload"
              action="#"
              accept=".xlsx,.xls"
              drag
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
            </el-upload>
          </div>
          
          <div slot="footer" class="dialog-footer">
            <el-button @click="importDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmImport" :disabled="uploadFileList.length === 0">确认导入</el-button>
          </div>
        </el-dialog>

        <!-- 操作按钮区域 -->
        <div class="drawer-footer">
          <el-button @click="handleEditDrawerClose">取消</el-button>
          <el-button type="primary" @click="handleSaveDraft">保存草稿</el-button>
          <el-button type="success" @click="handleSubmitConfirm">提交确认</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer title="供货协议详情" :visible.sync="detailDrawerVisible" direction="rtl" size="50%">
      <div class="drawer-content">
        <div class="detail-header">
          <span>{{ detailData.frameworkCode || '-' }}</span>
          <dict-tag class="ml10" :options="dict.type.protocol_status" :value="detailData.status" />
        </div>

        <!-- 协议基础 -->
        <div class="panel-title">协议基础</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="item"><b>收货公司：</b>{{ detailData.receiverCompanyName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>发货公司：</b>{{ detailData.senderCompanyName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>需求计划部门：</b>{{ detailData.receiverDeptName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>发货计划部门：</b>{{ detailData.senderDeptName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>收货仓库：</b>{{ detailData.receiverWarehouseName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>发货仓库：</b>{{ detailData.senderWarehouseName }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>收货联系人：</b>{{ detailData.receiverContact }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>收货电话：</b>{{ detailData.receiverPhone }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>发货联系人：</b>{{ detailData.senderContact }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>发货电话：</b>{{ detailData.senderPhone }}</div>
          </el-col>
        </el-row>

        <!-- 业务配置 -->
        <div class="panel-title">业务配置</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="item"><b>要货提前期：</b>{{ detailData.leadTimeHours }} 小时</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>打印机ID：</b>{{ detailData.printerId }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>箱标模板：</b>{{ detailData.boxLabelTemplate }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>看板模板：</b>{{ detailData.kanbanTemplate }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>需确认协议：</b>{{ yesNo(detailData.needSenderConfirmFramework) }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>需确认看板：</b>{{ yesNo(detailData.needSenderConfirmKanban) }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>当做送货单：</b>{{ yesNo(detailData.deliveryAsReceipt) }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>收货扫码要求：</b>{{ scanLabel(detailData.scanRequirement) }}</div>
          </el-col>
        </el-row>

        <!-- 时间信息 -->
        <div class="panel-title">时间信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="item"><b>生效时间：</b>{{ detailData.businessStartDate }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>到期时间：</b>{{ detailData.businessEndDate }}</div>
          </el-col>
        </el-row>

        <!-- 操作记录 -->
        <div class="panel-title">操作记录</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="item"><b>创建人：</b>{{ detailData.createBy }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>创建时间：</b>{{ detailData.createTime }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>更新人：</b>{{ detailData.updateBy }}</div>
          </el-col>
          <el-col :span="12">
            <div class="item"><b>更新时间：</b>{{ detailData.updateTime }}</div>
          </el-col>
          <el-col :span="24" v-if="detailData.remark">
            <div class="item"><b>备注：</b>{{ detailData.remark }}</div>
          </el-col>
        </el-row>

        <div class="drawer-footer">
          <el-button @click="detailDrawerVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail" v-hasPermi="['kanban:framework:edit']">编辑</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listSupplyFramework, updateSupplyFramework, addSupplyFramework, getSupplyFramework } from '@/api/kanban/supplyFramework'
import { listDept } from '@/api/system/dept'
import { generateTempSequenceNumber, generateFormalSequenceNumber } from '@/api/kanban/sequence'
import { getDicts } from '@/api/system/dict/data'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import * as XLSX from 'xlsx'

export default {
  name: 'SupplyFrameworkIndex',
  dicts: ['protocol_status'],
  components: { Treeselect },
  computed: {
    // 获取当前登录用户信息
    currentUser () {
      return this.$store.state.user
    }
  },
  data () {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        frameworkCode: undefined,
        receiverCompanyName: undefined,
        senderCompanyName: undefined,
        status: undefined
      },
      // 编辑抽屉相关
      editDrawerVisible: false,
      editDrawerTitle: '',
      editMode: 'add', // 'add' 或 'edit'
      editForm: {
        id: undefined,
        frameworkCode: undefined,
        status: "-30",
        receiverOrgId: undefined,
        receiverCompanyId: undefined,
        receiverCompanyName: undefined,
        senderOrgId: undefined,
        senderCompanyId: undefined,
        senderCompanyName: undefined,
        receiverDeptId: undefined,
        receiverDeptName: undefined,
        senderDeptId: undefined,
        senderDeptName: undefined,
        receiverWarehouseName: undefined,
        senderWarehouseName: undefined,
        receiverContact: undefined,
        receiverPhone: undefined,
        senderContact: undefined,
        senderPhone: undefined,
        businessStartDate: undefined,
        businessEndDate: undefined,
        leadTimeHours: 0,
        printerId: undefined,
        boxLabelTemplate: undefined,
        kanbanTemplate: undefined,
        needSenderConfirmFramework: 0,
        needSenderConfirmKanban: 0,
        deliveryAsReceipt: 0,
        scanRequirement: 0
      },
      editRules: {
        frameworkCode: [{ required: true, message: '请输入协议编码', trigger: 'blur' }],
        receiverDeptId: [{ required: true, message: '请选择需求计划部门', trigger: 'change' }],
        senderDeptId: [{ required: true, message: '请选择发货计划部门', trigger: 'change' }],
        receiverCompanyName: [{ required: true, message: '收货公司不能为空', trigger: 'blur' }],
        senderCompanyName: [{ required: true, message: '发货公司不能为空', trigger: 'blur' }],
        receiverWarehouseName: [{ required: true, message: '收货仓库不能为空', trigger: 'blur' }],
        senderWarehouseName: [{ required: true, message: '发货仓库不能为空', trigger: 'blur' }],
        businessStartDate: [{ required: true, message: '请选择生效时间', trigger: 'change' }],
        businessEndDate: [{ required: true, message: '请选择到期时间', trigger: 'change' }]
      },
      // 详情抽屉相关
      detailDrawerVisible: false,
      detailData: {},
      // 组织树相关
      deptOptions: [],
      // 物料明细相关
      materialList: [],
      materialBackupList: [], // 用于编辑取消时恢复数据
      // Excel导入相关
      importDialogVisible: false,
      uploadFileList: [],
      // 单位字典数据
      unitOptions: [],
      // 保存状态相关
      isSaving: false,
      savingText: '保存中...'
    }
  },
  created () {
    this.getList()
    this.getUnitOptions()
  },
  methods: {
    // 获取单位字典数据
    getUnitOptions() {
      getDicts('wuliao_unit').then(response => {
        this.unitOptions = response.data || []
      }).catch(error => {
        console.error('获取单位字典数据失败:', error)
      })
    },
    getList () {
      this.loading = true
      const params = { ...this.queryParams }

      // 处理协议日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginBusinessDate = this.dateRange[0]
        params.endBusinessDate = this.dateRange[1]
      }

      listSupplyFramework(params).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取数据失败:', error)
        this.$modal.msgError('获取数据失败，请重试')
        this.loading = false
      })
    },
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery () {
      this.dateRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        frameworkCode: undefined,
        receiverCompanyName: undefined,
        senderCompanyName: undefined,
        status: undefined
      }
      this.$refs.queryForm && this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 新增协议
    async handleAdd () {
      this.resetEditForm()
      this.editMode = 'add'
      this.editDrawerTitle = '新建供货协议'
      this.loadDeptOptions()

      // 生成临时协议编码
      try {
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        const key = `HT${year}${month}${day}`

        const response = await generateTempSequenceNumber(key, 4)
        if (response.code === 200) {
          // 确保在下一个tick中设置值，避免被resetEditForm清空

          this.$nextTick(() => {
            this.editForm.frameworkCode = response.msg
          })
        }
      } catch (error) {
        console.error('生成临时协议编码失败:', error)
        this.$modal.msgError('生成协议编码失败')
      }

      this.editDrawerVisible = true
    },
    // 编辑协议
    handleUpdate (row) {
      this.resetEditForm()
      this.editMode = 'edit'
      this.editDrawerTitle = '编辑供货协议'
      this.loadDeptOptions()

      if (row.id) {
        getSupplyFramework(row.id).then(res => {
          this.editForm = Object.assign(this.editForm, res.data || {})
          this.editDrawerVisible = true
        })
      }
    },
    // 查看详情
    handleView (row) {
      if (row.id) {
        getSupplyFramework(row.id).then(res => {
          this.detailData = res.data || {}
          this.detailDrawerVisible = true
        })
      }
    },
    // 从详情页面跳转到编辑
    handleEditFromDetail () {
      this.detailDrawerVisible = false
      this.editMode = 'edit'
      this.editDrawerTitle = '编辑供货协议'
      this.editForm = Object.assign({}, this.detailData)
      this.editDrawerVisible = true
    },
    // 重置编辑表单
    resetEditForm () {
      this.editForm = {
        id: undefined,
        frameworkCode: undefined,
        status: "10",
        receiverOrgId: undefined,
        receiverCompanyId: undefined,
        receiverCompanyName: undefined,
        senderOrgId: undefined,
        senderCompanyId: undefined,
        senderCompanyName: undefined,
        receiverDeptId: undefined,
        receiverDeptName: undefined,
        senderDeptId: undefined,
        senderDeptName: undefined,
        receiverWarehouseName: undefined,
        senderWarehouseName: undefined,
        receiverContact: undefined,
        receiverPhone: undefined,
        senderContact: undefined,
        senderPhone: undefined,
        businessStartDate: undefined,
        businessEndDate: undefined,
        leadTimeHours: 0,
        printerId: undefined,
        boxLabelTemplate: undefined,
        kanbanTemplate: undefined,
        needSenderConfirmFramework: 0,
        needSenderConfirmKanban: 0,
        deliveryAsReceipt: 0,
        scanRequirement: 0
      }
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
    },
    // 关闭编辑抽屉
    handleEditDrawerClose () {
      this.editDrawerVisible = false
      this.resetEditForm()
    },
    // 保存草稿
    async handleSaveDraft () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return

        // 显示保存状态
        this.isSaving = true
        this.savingText = '保存草稿中...'

        try {
          // 如果是新增模式，生成正式协议编码
          if (this.editMode === 'add') {
            try {
              const today = new Date()
              const year = today.getFullYear()
              const month = String(today.getMonth() + 1).padStart(2, '0')
              const day = String(today.getDate()).padStart(2, '0')
              const key = `HT${year}${month}${day}`

              const response = await generateFormalSequenceNumber(key, 4)
              if (response.code === 200) {
                this.editForm.frameworkCode = response.msg
              } else {
                this.$modal.msgError('生成协议编码失败')
                return
              }
            } catch (error) {
              console.error('生成正式协议编码失败:', error)
              this.$modal.msgError('生成协议编码失败')
              return
            }
          }

          const req = this.editMode === 'edit' ? updateSupplyFramework(this.editForm) : addSupplyFramework(this.editForm)
          await req
          this.$message.success('保存成功')
          this.editDrawerVisible = false
          this.getList()
        } catch (error) {
          console.error('保存失败:', error)
          this.$modal.msgError('保存失败，请重试')
        } finally {
          // 隐藏保存状态
          this.isSaving = false
        }
      })
    },
    // 提交确认
    async handleSubmitConfirm () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return

        // 显示保存状态
        this.isSaving = true
        this.savingText = '提交确认中...'

        try {
          // 如果是新增模式，生成正式协议编码
          if (this.editMode === 'add') {
            try {
              const today = new Date()
              const year = today.getFullYear()
              const month = String(today.getMonth() + 1).padStart(2, '0')
              const day = String(today.getDate()).padStart(2, '0')
              const key = `HT${year}${month}${day}`

              const response = await generateFormalSequenceNumber(key, 4)
              if (response.code === 200) {
                this.editForm.frameworkCode = response.msg
              } else {
                this.$modal.msgError('生成协议编码失败')
                return
              }
            } catch (error) {
              console.error('生成正式协议编码失败:', error)
              this.$modal.msgError('生成协议编码失败')
              return
            }
          }

          const payload = { ...this.editForm, status: 20 }
          const req = this.editMode === 'edit' ? updateSupplyFramework(payload) : addSupplyFramework(payload)
          await req
          this.$message.success('已提交确认')
          this.editDrawerVisible = false
          this.getList()
        } catch (error) {
          console.error('提交失败:', error)
          this.$modal.msgError('提交失败，请重试')
        } finally {
          // 隐藏保存状态
          this.isSaving = false
        }
      })
    },
    handleConfirm (row) {
      this.$confirm('确认通过该协议？', '提示', { type: 'warning' }).then(() => {
        const data = { ...row, status: 0 }
        return updateSupplyFramework(data)
      }).then(() => {
        this.$message.success('操作成功')
        this.getList()
      }).catch(() => { })
    },
    handleVoid (row) {
      this.$confirm('确认作废该协议？', '提示', { type: 'warning' }).then(() => {
        const data = { ...row, status: -10 }
        return updateSupplyFramework(data)
      }).then(() => {
        this.$message.success('操作成功')
        this.getList()
      }).catch(() => { })
    },
    // 详情页面辅助方法
    yesNo (v) { return v === 1 ? '是' : '否' },
    scanLabel (v) { return v === 1 ? '必须扫码' : v === 2 ? '建议扫码' : '不要求' },
    // 判断当前用户是否为发货方
    isCurrentUserReceiver (row) {
      // 获取当前用户的部门ID
      const currentUserDeptId = this.$store.state.user.dept ? this.$store.state.user.dept.deptId : null
      // 判断当前用户的部门ID是否与协议的发货部门ID匹配
      debugger
      return row.senderDeptId === currentUserDeptId
    },
    // 组织树相关方法
    loadDeptOptions () {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId")
      })
    },
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 收货部门选择处理
    handleReceiverDeptChange (value) {
      if (value) {
        const selectedNode = this.findNodeById(this.deptOptions, value)
        if (selectedNode) {
          // 查找对应的公司名称
          const companyNode = this.findCompanyNode(selectedNode)
          if (companyNode) {
            // 设置公司名称和ID
            this.editForm.receiverCompanyName = companyNode.deptName
            this.editForm.receiverCompanyId = companyNode.deptId
          } else {
            // 如果找不到公司，使用当前部门作为公司
            this.editForm.receiverCompanyName = selectedNode.deptName
            this.editForm.receiverCompanyId = selectedNode.deptId
          }

          // 自动填充收货部门为选择的部门
          this.editForm.receiverDeptName = selectedNode.deptName
          // 自动填充收货仓库为选择的部门名称
          this.editForm.receiverWarehouseName = selectedNode.deptName
          // 自动填充收货联系人为部门负责人
          this.editForm.receiverContact = selectedNode.leader || ''
          // 自动填充收货电话为部门电话
          this.editForm.receiverPhone = selectedNode.phone || ''
        }
      } else {
        // 清空相关字段
        this.editForm.receiverCompanyName = ''
        this.editForm.receiverCompanyId = ''
        this.editForm.receiverDeptName = ''
        this.editForm.receiverWarehouseName = ''
        this.editForm.receiverContact = ''
        this.editForm.receiverPhone = ''
      }
    },
    // 发货部门选择处理
    handleSenderDeptChange (value) {
      if (value) {
        const selectedNode = this.findNodeById(this.deptOptions, value)
        if (selectedNode) {
          // 查找对应的公司名称
          const companyNode = this.findCompanyNode(selectedNode)
          if (companyNode) {
            // 设置公司名称和ID
            this.editForm.senderCompanyName = companyNode.deptName
            this.editForm.senderCompanyId = companyNode.deptId
          } else {
            // 如果找不到公司，使用当前部门作为公司
            this.editForm.senderCompanyName = selectedNode.deptName
            this.editForm.senderCompanyId = selectedNode.deptId
          }

          // 自动填充发货部门为选择的部门
          this.editForm.senderDeptName = selectedNode.deptName
          // 自动填充发货仓库为选择的部门名称
          this.editForm.senderWarehouseName = selectedNode.deptName
          // 自动填充发货联系人为部门负责人
          this.editForm.senderContact = selectedNode.leader || ''
          // 自动填充发货电话为部门电话
          this.editForm.senderPhone = selectedNode.phone || ''
        }
      } else {
        // 清空相关字段
        this.editForm.senderCompanyName = ''
        this.editForm.senderCompanyId = ''
        this.editForm.senderDeptName = ''
        this.editForm.senderWarehouseName = ''
        this.editForm.senderContact = ''
        this.editForm.senderPhone = ''
      }
    },
    // 查找对应的公司节点
    findCompanyNode (node) {
      if (!node) return null

      // 如果当前节点的parent_id为0，说明它就是顶级公司
      if (node.parentId === 0) {
        return node
      }

      // 如果当前节点的parent_id为100（若依科技的ID），说明它是子公司
      if (node.parentId === 100) {
        return node
      }

      // 否则向上查找父节点
      const parentNode = this.findNodeById(this.deptOptions, node.parentId)
      if (parentNode) {
        return this.findCompanyNode(parentNode)
      }

      return null
    },
    // 查找上级部门
    findParentNode (node) {
      if (!node || !node.parentId || node.parentId === 0) {
        return null
      }
      return this.findNodeById(this.deptOptions, node.parentId)
    },
    // 根据ID查找节点
    findNodeById (nodes, id) {
      for (let node of nodes) {
        if (node.deptId === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id)
          if (found) return found
        }
      }
      return null
    },
    
    // 物料明细相关方法
    // 添加物料
    handleAddMaterial() {
      const newMaterial = {
        id: undefined,
        frameworkId: this.editForm.id,
        frameworkCode: this.editForm.frameworkCode,
        materialCode: '',
        materialName: '',
        materialUnit: '',
        unitPrice: 0,
        taxRate: 0,
        packageType: '',
        packageCapacity: 0,
        minOrderQty: 0,
        editing: true,
        isNew: true // 标记为新增行
      }
      this.materialList.push(newMaterial)
      this.$message.success('已添加新物料行，请填写物料信息')
    },
    
    // 编辑物料
    handleEditMaterial(row, index) {
      // 检查是否有其他行正在编辑
      const editingIndex = this.materialList.findIndex(item => item.editing === true)
      if (editingIndex !== -1 && editingIndex !== index) {
        this.$message.warning('请先保存或取消当前编辑的物料')
        return
      }
      
      // 备份原始数据
      this.materialBackupList[index] = { ...row }
      this.$set(this.materialList, index, { ...row, editing: true })
    },
    
    // 保存物料
    handleSaveMaterial(row, index) {
      // 验证必填字段
      if (!row.materialCode || !row.materialName) {
        this.$message.warning('物料编码和物料名称不能为空')
        return
      }
      
      // 验证数值字段
      if (row.unitPrice < 0) {
        this.$message.warning('单价不能为负数')
        return
      }
      
      if (row.taxRate < 0 || row.taxRate > 100) {
        this.$message.warning('税率必须在0-100之间')
        return
      }
      
      if (row.packageCapacity < 0 || row.minOrderQty < 0) {
        this.$message.warning('包装容量和最小订货量不能为负数')
        return
      }
      
      // 检查物料编码是否重复
      const duplicateIndex = this.materialList.findIndex((item, idx) => 
        idx !== index && item.materialCode === row.materialCode
      )
      if (duplicateIndex !== -1) {
        this.$message.warning('物料编码不能重复')
        return
      }
      
      // 保存数据
      this.$set(this.materialList, index, { ...row, editing: false, isNew: false })
      this.$message.success('保存成功')
    },
    
    // 取消编辑物料
    handleCancelEditMaterial(row, index) {
      if (row.isNew || row.id === undefined) {
        // 新增的行，直接删除
        this.materialList.splice(index, 1)
        this.$message.info('已取消新增物料')
      } else {
        // 编辑的行，恢复原始数据
        this.$set(this.materialList, index, { ...this.materialBackupList[index], editing: false })
        this.$message.info('已取消编辑')
      }
    },
    
    // 删除物料
    handleDeleteMaterial(index) {
      const material = this.materialList[index]
      
      // 如果正在编辑，先提示保存
      if (material.editing) {
        this.$message.warning('请先保存或取消编辑后再删除')
        return
      }
      
      this.$confirm(`确认删除物料"${material.materialName || material.materialCode || '未命名物料'}"？`, '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }).then(() => {
        this.materialList.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // Excel导入
    handleImportMaterial() {
      this.importDialogVisible = true
      this.uploadFileList = []
    },
    
    // 文件选择变化
    handleFileChange(file, fileList) {
      this.uploadFileList = fileList
    },
    
    // 文件移除
    handleFileRemove(file, fileList) {
      this.uploadFileList = fileList
    },
    
    // 上传前验证
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.type === 'application/vnd.ms-excel'
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10MB!')
        return false
      }
      return false // 阻止自动上传
    },
    
    // 确认导入
    handleConfirmImport() {
      if (this.uploadFileList.length === 0) {
        this.$message.warning('请选择要导入的文件')
        return
      }
      
      const file = this.uploadFileList[0].raw
      if (!file) {
        this.$message.error('文件读取失败，请重新选择文件')
        return
      }
      
      const reader = new FileReader()
      
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const sheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[sheetName]
          const jsonData = XLSX.utils.sheet_to_json(worksheet)
          
          this.processImportData(jsonData)
        } catch (error) {
          console.error('文件解析错误:', error)
          this.$message.error('文件解析失败，请检查文件格式')
        }
      }
      
      reader.onerror = (error) => {
        console.error('文件读取错误:', error)
        this.$message.error('文件读取失败')
      }
      
      reader.readAsArrayBuffer(file)
    },
    
    // 处理导入数据
    processImportData(jsonData) {
      if (!jsonData || jsonData.length === 0) {
        this.$message.warning('文件中没有有效数据')
        return
      }
      
      let successCount = 0
      let skipCount = 0
      const errors = []
      
      jsonData.forEach((row, index) => {
        try {
          // 数据映射和验证
          const material = {
            id: undefined,
            frameworkId: this.editForm.id,
            frameworkCode: this.editForm.frameworkCode,
            materialCode: row['物料编码'] || row['materialCode'] || '',
            materialName: row['物料名称'] || row['materialName'] || '',
            materialUnit: row['单位'] || row['materialUnit'] || '',
            unitPrice: parseFloat(row['单价'] || row['unitPrice'] || 0),
            taxRate: parseFloat(row['税率'] || row['taxRate'] || 0),
            packageType: row['包装类型'] || row['packageType'] || '',
            packageCapacity: parseInt(row['包装容量'] || row['packageCapacity'] || 0),
            minOrderQty: parseInt(row['最小订货量'] || row['minOrderQty'] || 0),
            editing: false,
            isNew: true
          }
          
          // 验证必填字段
          if (!material.materialCode || !material.materialName) {
            errors.push(`第${index + 2}行：物料编码和物料名称不能为空`)
            return
          }
          
          // 检查是否重复
          const existingIndex = this.materialList.findIndex(item => 
            item.materialCode === material.materialCode
          )
          if (existingIndex !== -1) {
            skipCount++
            return
          }
          
          // 验证数值范围
          if (material.unitPrice < 0) {
            errors.push(`第${index + 2}行：单价不能为负数`)
            return
          }
          
          if (material.taxRate < 0 || material.taxRate > 100) {
            errors.push(`第${index + 2}行：税率必须在0-100之间`)
            return
          }
          
          if (material.packageCapacity < 0 || material.minOrderQty < 0) {
            errors.push(`第${index + 2}行：包装容量和最小订货量不能为负数`)
            return
          }
          
          // 添加到列表
          this.materialList.push(material)
          successCount++
          
        } catch (error) {
          errors.push(`第${index + 2}行：数据格式错误`)
        }
      })
      
      // 显示导入结果
      let message = `导入完成！成功导入${successCount}条记录`
      if (skipCount > 0) {
        message += `，跳过重复记录${skipCount}条`
      }
      if (errors.length > 0) {
        message += `，失败${errors.length}条`
        console.warn('导入错误详情:', errors)
        this.$message.warning(message + '，详细错误请查看控制台')
      } else {
        this.$message.success(message)
      }
      
      this.importDialogVisible = false
      this.uploadFileList = []
    },
    
    // 下载模板
    handleExportTemplate() {
      // 创建模板数据
      const templateData = [
        {
          '物料编码': 'MAT001',
          '物料名称': '示例物料1',
          '单位': '个',
          '单价': 10.50,
          '税率': 13,
          '包装类型': '箱',
          '包装容量': 100,
          '最小订货量': 10
        },
        {
          '物料编码': 'MAT002',
          '物料名称': '示例物料2',
          '单位': 'kg',
          '单价': 25.80,
          '税率': 13,
          '包装类型': '袋',
          '包装容量': 50,
          '最小订货量': 5
        }
      ]
      
      // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(templateData)
      
      // 设置列宽
      const colWidths = [
        { wch: 15 }, // 物料编码
        { wch: 20 }, // 物料名称
        { wch: 8 },  // 单位
        { wch: 10 }, // 单价
        { wch: 8 },  // 税率
        { wch: 12 }, // 包装类型
        { wch: 12 }, // 包装容量
        { wch: 15 }  // 最小订货量
      ]
      ws['!cols'] = colWidths
      
      // 为单位列添加数据验证（下拉列表）
      if (this.unitOptions && this.unitOptions.length > 0) {
        const unitValues = this.unitOptions.map(item => item.dictLabel).join(',')
        
        // 设置单位列的数据验证范围（从第2行到第999行）
        const unitColIndex = 2 // 单位列是第3列（索引为2）
        
        // 创建数据验证对象
        if (!ws['!dataValidation']) {
          ws['!dataValidation'] = []
        }
        
        // 为单位列的每一行添加下拉验证（使用简单的逗号分隔列表）
        for (let row = 1; row <= 999; row++) {
          const cellAddress = XLSX.utils.encode_cell({ r: row, c: unitColIndex })
          ws['!dataValidation'].push({
            sqref: cellAddress,
            type: 'list',
            formula1: `"${unitValues}"`,
            allowBlank: true,
            showInputMessage: true,
            promptTitle: '单位选择',
            prompt: '请从下拉列表中选择单位',
            showErrorMessage: true,
            errorTitle: '输入错误',
            error: '请选择有效的单位'
          })
        }
      }
      
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '物料明细模板')
      
      // 下载文件
      XLSX.writeFile(wb, '物料明细导入模板.xlsx')
      this.$message.success('模板下载成功')
    }
  }
}
</script>

<style scoped>
.text-right {
  text-align: right;
}

/* 抽屉样式 */

.drawer-content {
  padding: 20px;
  padding-bottom: 80px; /* 为底部按钮栏预留空间 */
}

/* 保存状态遮罩层样式 */
.saving-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.saving-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.saving-content .el-icon {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 15px;
}

.saving-text {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  border-top: 1px solid #e8e8e8;
  background: #fff;
  text-align: right;
}

.form-header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  margin: 8px 10px 25px 10px;
}

.panel-title {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  margin: 8px 10px 15px 10px;
}

.item {
  margin: 6px 0;
}

.ml10 {
  margin-left: 10px;
}

.material-detail-section {
  margin: 20px 0;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.material-toolbar {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.material-table {
  width: 100%;
}

.import-content {
  padding: 10px 0;
}

.import-tips {
  margin-bottom: 20px;
}

.import-actions {
  text-align: center;
}

.dialog-footer {
  text-align: right;
}
</style>
